const express = require('express');
const RestResult = require('../RestResult');
const router = express.Router();
const async = require('async');
const log = require('../utils/logUtil').log();

const UserEntity = require("../models/User").UserEntity;


/* GET users listing. */
router.get('/', function (req, res, next) {

});


router.post('/register', function (req, res, next) {
    log.debug(req.body);
    let userName = req.body.name;
    let userPwd = req.body.pwdText;
    let userStudentId = req.body.studentID;
    let userEmail = req.body.email;
    let userMobile = req.body.mobile;
    let userSex = req.body.sex;
    let userIsAdmin = false;

    let resData = new RestResult();

    async.series([
            function (callback) {
                UserEntity.findOne({name: userName}, callback);
            },
            function (callback) {
                UserEntity.findOne({studentID: userStudentId}, callback);
            },
            function (callback) {
                UserEntity.findOne({email: userEmail}, callback);
            },
            function (callback) {
                UserEntity.findOne({mobile: userMobile}, callback);
            }
        ],
        function (err, docs) {
            log.debug(docs);
            if (err) {
                resData.code = 1;
                resData.errorReason = RestResult.SERVER_EXCEPTION_ERROR_DESCRIPTION;
                res.send(resData);
            }

            let user = {
                name: userName,
                studentID: userStudentId,
                email: userEmail,
                mobile: userMobile,
            }
            let trans = {
                name: '姓名',
                studentID: '学号',
                email: '邮箱',
                mobile: '手机号',
            };

            for (let doc of docs) {
                if (doc) {
                    let {name, studentID, email, mobile} = doc._doc;
                    let doc_user = {
                        name: name,
                        studentID: studentID,
                        email: email,
                        mobile: mobile
                    };
                    for (let prop in doc_user) {
                        if (user[prop] == doc[prop]) {
                            resData.code = 1;
                            resData.errorReason = trans[prop] + '已存在！';
                            res.send(resData);
                            return;
                        }
                    }
                }
            }


            let userEntity = new UserEntity({
                name: userName,
                pwdText: userPwd,
                studentID: userStudentId,
                email: userEmail,
                mobile: userMobile,
                sex: userSex,
                isAdmin:userIsAdmin
            });
            console.log(userEntity);
            userEntity.save(function (err, data) {
                if (err) {
                    resData.code = 1;
                    resData.errorReason = RestResult.SERVER_EXCEPTION_ERROR_DESCRIPTION;
                    res.send(resData);
                }
                else {
                    resData.code = 0;
                    resData.returnValue = data;
                }
                res.send(resData);
            });
        });

});

router.post('/login', function (req, res, next) {
    let studentID = req.body.studentID;
    let userPwd = req.body.pwdText;

    log.debug(studentID);
    log.debug(userPwd);

    // console.log(userName);
    // console.log(userPwd);
    UserEntity.findOne({studentID: studentID, pwdText: userPwd}, function (err, user) {
        let resData = new RestResult;
        if (err) {
            console.log(err)
            res.send(RestResult.SERVER_EXCEPTION_ERROR_DESCRIPTION);
        }
        if (user) {
            resData.code = 0;
            resData.returnValue = user;
            res.send(resData);
        }
        else {
            resData.code = 3;
            resData.errorReason = "用户名不存在或密码错误";
            res.send(resData);
        }
    });
});
//修改密码
router.post('/changePwd', function (req, res, next) {

    let userId = req.body.userId;
    log.debug(userId);
    let userNeWPwd = req.body.newPwd;
    let userNeWPwd2 = req.body.newPwd2;
    log.debug(userNeWPwd);

    UserEntity.findById(userId, function (err, user) {
        let resData = new RestResult;
        if (err) {
            resData.code = 1;
            resData.errorReason = RestResult.SERVER_EXCEPTION_ERROR_DESCRIPTION;
            log.debug(resData);
            res.send(resData);
        }
        log.debug(user);
        if (user) {
            if (userNeWPwd != userNeWPwd2) {
                resData.code = 2;
                resData.errorReason = "密码输入不一致！";
                log.debug(resData);
                res.send(resData);

            }
            else {
                UserEntity.findOneAndUpdate({_id: userId}, {$set: {"pwdText": userNeWPwd}},function (err,data) {
                    if (err) {
                        resData.code = 1;
                        resData.errorReason = RestResult.SERVER_EXCEPTION_ERROR_DESCRIPTION;
                        log.debug(resData);
                        res.send(resData);
                    }
                    else {
                        resData.code = 0;
                        log.debug(data);
                        resData.returnValue = data;
                        log.debug(resData);
                        res.send(resData);

                    }
                });

            }
        }

    });

});

router.post('/changeInformation', function (req,res,next) {
    let userId = req.body._id;
    let userName = req.body.name;
    let userStudentId = req.body.studentID;
    let userEmail = req.body.email;
    let userMobile = req.body.mobile;
    let userSex = req.body.sex;

    let resData = new RestResult();

    async.series([
            function (callback) {
                UserEntity.findOne({name: userName}, callback);
            },
            function (callback) {
                UserEntity.findOne({studentID: userStudentId}, callback);
            },
            function (callback) {
                UserEntity.findOne({email: userEmail}, callback);
            },
            function (callback) {
                UserEntity.findOne({mobile: userMobile}, callback);
            }
        ],
        function (err, docs) {
            log.debug(docs)
            if (err) {
                resData.code = 1;
                resData.errorReason = RestResult.SERVER_EXCEPTION_ERROR_DESCRIPTION;
                res.send(resData);
            }

            let user = {
                name: userName,
                studentID: userStudentId,
                email: userEmail,
                mobile: userMobile,
            }
            let trans = {
                name: '姓名',
                studentID: '学号',
                email: '邮箱',
                mobile: '手机号',
            };

            for (let doc of docs) {
                if (doc) {
                    let {name, studentID, email, mobile} = doc._doc;
                    let doc_user = {
                        name: name,
                        studentID: studentID,
                        email: email,
                        mobile: mobile
                    };
                    for (let prop in doc_user) {
                        if (user[prop] == doc[prop]) {
                            resData.code = 1;
                            resData.errorReason = trans[prop] + '已存在！';
                            res.send(resData);
                            return;
                        }
                    }
                }
            }


            let userEntity = new UserEntity({
                name: userName,
                pwdText: userPwd,
                studentID: userStudentId,
                email: userEmail,
                mobile: userMobile,
                sex: userSex
            });
            console.log(userEntity);
            userEntity.updateOne(
                {_id: userId},
                {
                    $set: {
                        name: userName,
                        studentID: userStudentId,
                        email: userEmail,
                        mobile: userMobile,
                        sex: userSex
                    }
                },
                function (err, user) {
                    if (err) {
                        resData.code = 1;
                        resData.errorReason = RestResult.SERVER_EXCEPTION_ERROR_DESCRIPTION;
                        res.send(resData);
                    }
                    else {
                        resData.code = 0;
                        resData.returnValue = user;
                        res.send(resData);
                    }
                });
        });

});
//从数据库取出数据
router.post('/getInformation', function (req, res, next) {
    let userId = req.body.userId;
    let resData = new RestResult;
    log.debug(userId);
    if (!userId) {
        resData.code = RestResult.ILLEGAL_ARGUMENT_ERROR_CODE;
        resData.errorReason = '未登录!';
        res.send(resData);
        return;
    }
    UserEntity.findOne({_id: userId}, function (err, data) {
        log.debug(data);
        if (err) {
            resData.code = 1;
            resData.errorReason = RestResult.SERVER_EXCEPTION_ERROR_DESCRIPTION;
            res.send(resData);
        }
        else {
            resData.code = 0;
            resData.returnValue = data;
            res.send(resData);
        }
    });

});
//从数据库取出所有姓名与手机号码
router.post('/getUserInformation',function (req,res,data) {
    let resData = new RestResult;
    UserEntity.find({},function (err,docs) {
        if(err){
            resData.code = 1;
            resData.errorReason = RestResult.SERVER_EXCEPTION_ERROR_DESCRIPTION;
            res.send(resData);
            return ;
        }
        if(docs){
            let result =[];
            for(let i = 0;i<docs.length;i++){
                result[i] = {};
                result[i].name = docs[i].name;
                result[i].mobile = docs[i].mobile;
            }
            resData.code = 0;
            resData.returnValue = result;
            res.send(resData);
        }

    })
});
/*router.post('/getStudentNameForApp',function (req, res, next){
    let userId = req.body.userId;
    let resData = new RestResult;
    log.debug(userId);
    if (!userId) {
        resData.code = RestResult.ILLEGAL_ARGUMENT_ERROR_CODE;
        resData.errorReason = '未登录!';
        res.send(resData);
        return;
    }
    UserEntity.findOne({_id: userId}, function (err, data) {
        log.debug(data);
        if (err) {
            resData.code = 1;
            resData.errorReason = RestResult.SERVER_EXCEPTION_ERROR_DESCRIPTION;
            res.send(resData);
        }
        else {
            resData.code = 0;
            resData.returnValue = data;
            res.send(resData);
        }
    });
});*/

module.exports = router;